package com.lele.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lele.utils.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 权限不足
 */
@Component
public class MyaccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        Result<String> result = Result.ERROR("您的权限不足");
        result.setCode(401);
        String s = new ObjectMapper().writeValueAsString(result);
        //TODO getWriter和outputStream的区别
/*        PrintWriter writer = response.getWriter();
        //ServletOutputStream outputStream = response.getOutputStream();
        writer.print(s);
        writer.flush();
        writer.close();*/
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.print(s);
        outputStream.flush();
        outputStream.close();
    }
}
